// pagesGame/pages/saolei/index.js
const back =  wx.getBackgroundAudioManager();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    row:7,//方格行数
    col:7,//方格列数
    mineCount:3,//地雷个数
    gameOverInfo:'',
    a : [],
    tempA:[],
    box : {},
    cellList:[], // {width:50,height:50,row:0,col:0,inner:'',background:'yellowgreen',}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  // onLoad(options) {
  //   this.initGame();
  // },
  
  backmusic:function(){
    player();
    function player(){
      back.title = "HEAVEN's Door"
      back.src = "https://api.sdyuedou.com/ydimg/ydmic/385fc638af018be854b768f8ec919029.mp3"
      back.onEnded(()=>{
        player();
      })
    }
  },
  onLoad: function () {
    //背景音乐播放
    this.backmusic();
    this.initGame();
  },
  onUnload(){
    back.stop();
    back = null;
  },
  // onLoad(options) {
  //   this.initGame();
  // },
  restart(){
    this.setData({
      gameOverInfo:'',
      a : [],
      tempA:[],
      box : {},
      cellList:[],
      gameOverInfoEle : ""
    })
    this.initGame();
  },
  initGame(){
    var that = this;
    that.data.tempA = [];
    for (var i = 0; i < this.data.row * this.data.col; i++) {
      that.data.tempA[i] = i;
    }
    for (var i = 0; i < this.data.mineCount; i++) {
        let randomIndex = Math.floor(Math.random()*(that.data.tempA.length - i));
        let randomNumber = that.data.tempA.splice(randomIndex,1)[0];
        this.data.a.push(randomNumber);
    }
    that.setData({
      tempA: that.data.tempA,
    })
    this.data.box.width = 100 * this.data.col;
    this.data.box.height = 100 * this.data.row;
    that.setData({
      box: that.data.box
    })
    for (var i = 0; i < this.data.row; i++) {
        for (var j = 0; j < this.data.col; j++) {
          var cell = {background:'',inner:''};
          cell.row = i;
          cell.col = j;
          // console.log('cell',cell)
          that.data.cellList.push(cell);
        }
    }
    that.setData({
      cellList: that.data.cellList
    })
  },
  bindClick(e){
    console.log('bindClick',e)
    var item = e.currentTarget.dataset.item;
    var index = e.currentTarget.dataset.index;
    var row = item.row;
    var col = item.col;
    var cell = this.data.cellList[index];
    // console.log('item',item)
    // console.log('index',index)
    // console.log('row',row)
    // console.log('col',col)
    // console.log('cell',cell)

    // 鼠标左键翻开格子
    if (this.boom(row,col,index) == -1){
        cell.inner = "💣";
        // alert("你输啦!");
        // that.data.gameOverInfoEle = "很遗憾，你输啦！";
        this.setData({
          gameOverInfoEle : "很遗憾，你输啦！"
        })
        // if(gameOverInfoEle.classList.contains("green")){
        //     gameOverInfoEle.classList.remove("green");
        // }
        // gameOverInfoEle.classList.add("red");
        cell.background = "red";
        this.gameOver();
    }else{
      this.removeBlank(row,col,index);
      if (this.isWin()){
        // alert("恭喜你，你赢啦!");
        // that.data.gameOverInfoEle = "恭喜你，你赢啦!";
        this.setData({
          gameOverInfoEle : "恭喜你，你赢啦!"
        })
        // if(gameOverInfoEle.classList.contains("red")){
        //     gameOverInfoEle.classList.remove("red");
        // }
        // gameOverInfoEle.classList.add("green");
        cell.background = "green";
        this.gameOver();
      }
    }
    this.data.cellList[index] = cell;
    // console.log('that.data.cellList',this.data.cellList)
    this.setData({
      cellList: this.data.cellList
    })
  },
  longClick(e){
    console.log('longClick',e)
    var item = e.currentTarget.dataset.item;
    var index = e.currentTarget.dataset.index;
    var row = item.row;
    var col = item.col;
    var cell = this.data.cellList[index];
    // 鼠标右键用旗帜标记地雷
    if (cell.inner == ""){
      cell.inner = "🚩";
      cell.background = "#ffff00";
      if (this.isWin()){
          // alert("恭喜你，你赢啦!");
          // gameOverInfoEle.inner = "恭喜你，你赢啦!";
          this.setData({
            gameOverInfoEle : "恭喜你，你赢啦!"
          })
          // if(gameOverInfoEle.classList.contains("red")){
          //     gameOverInfoEle.classList.remove("red");
          // }
          // gameOverInfoEle.classList.add("green");
          cell.background = "green";
          this.gameOver();
      }
    }else if(cell.inner == "🚩"){
      cell.inner = "";
      cell.background = "transparent";
    }
    this.data.cellList[index] = cell;
    this.setData({
      cellList: this.data.cellList
    })
  },
  // 判断地图上某个坐标是否在数组（保存地雷索引的数组）中（用来判断某格是否是雷）
  include(x,y,arr) {
    for (let i = 0; i < arr.length; i++) {
        if(x * this.data.col + y == arr[i]){
            return true;
        }
    }
    return false;
  },
  // 用来判断坐标是否出界
  isOutOfBounds(x, y) {
    if(x < 0 || y < 0 || x >= this.data.row || y >= this.data.col){
        return true;
    }else{
        return false;
    }
  },
  // 用来返回某个坐标周围的雷数
  boom(x,y) {
    let count = 0;
    if (this.include(x,y,this.data.a)){
        return -1;
    }
    for (let i = (x - 1); i < (x + 2); i++) {
        for (let j = (y - 1); j < (y + 2); j++) {
            if(i == x && j == y){
                continue;
            }else{
                if(!this.isOutOfBounds(i,j)){
                    if(this.include(i,j,this.data.a)){
                        count++;
                    }
                }
            }
        }
    }
    return count;
  },
  // 返回某个坐标的DOM对象
  findCell(x, y,index) {
    // let cells = document.querySelectorAll(".cell");
    // return cells[x * row + y];
    for(var index in this.data.cellList){
      var cell = this.data.cellList[index];
      if(cell.row == x && cell.col == y){
        console.log('cell',cell)
        return cell;
      }
    }

  },
  // 自动翻开无雷区域
  removeBlank(x,y,index) {
    var that = this;
    console.log('removeBlank',x+'--'+y);
    var cell = this.data.cellList[index];
    let boomCount = this.boom(x,y);
    if(boomCount == 0){
      cell.inner = "0";
      cell.background = "yellowgreen";
      let temp = 0;
      for (let i = (x - 1); i < (x + 2); i++) {
        for (let j = (y - 1); j < (y + 2); j++) {
            temp++;
            if(!(i == x && j == y)){
                if(!that.isOutOfBounds(i,j)){
                  // console.log('this.findCell(i,j)',this.findCell(i,j))
                  if (that.data.cellList[index].inner != ""){
                    continue;
                  }
                  let boomCount1 = that.boom(i,j);
                  if(boomCount1 != 0){
                    that.data.cellList[index].inner = boomCount1;
                    that.data.cellList[index].background = "yellowgreen";
                  }else{
                    that.removeBlank(i,j,index);
                  }
                }
            }
        }
      }
    }else{
      cell.inner = boomCount;
      cell.background = "yellowgreen";
      that.data.cellList[index] = cell;
    }
    
    this.setData({
      cellList: this.data.cellList
    })
  },
  // 判断是否胜利
  isWin() {
    let cells = this.data.cellList;
    let blankCount = 0;//未翻开的空白格的数量
    let flagCount = 0;//标记旗帜的数量
    for (let i = 0; i < cells.length; i++) {
        if(cells[i].inner == ""){
            blankCount++;
        }else if(cells[i].inner == "🚩"){
            flagCount++;
        }
    }
    if (blankCount > this.data.mineCount){
        return false;// 空白格大于雷数，说明还有未翻开的无雷格子
    }else if (blankCount == this.data.mineCount){
        if (flagCount == 0){
            return true;//空白格等于雷数，同时旗帜数为0，说明玩家没有插旗，所有空白格都是地雷
        }else{
            return false;
        }
    }else{
        if (blankCount == 0){
            if(flagCount == this.data.mineCount){
                return true;//空白格等于零，说明没有未翻开的格子，而旗帜数等于雷数，所有旗帜格下都是地雷
            }
        }else{
            if (blankCount + flagCount == this.data.mineCount){
                return true;//空白格小于雷数且不等于零，说明玩家已经用旗帜标记了部分地雷，如果空白格数加旗帜格数等于雷数，说明空白格都是地雷
            }
        }
        return false;
    }
  },
  // 切换成游戏结束后的地图（所有雷和雷数标记显示出来）
  gameOver() {
    // let cells = document.querySelectorAll(".cell");
    let cells = this.data.cellList;
    let index = 0;
    for (let i = 0; i < this.data.row; i++) {
        for (let j = 0; j < this.data.col; j++) {
            if(this.data.a.includes(index)){
                cells[index].inner = "💣";
                cells[index].background = "orange";
            }else{
                let boomCount = this.boom(i,j);
                cells[index].inner = boomCount;
                cells[index].background = "yellowgreen";
            }
            index++;
        }
    }
  }
  
})
